package com.gin.pixiv.deserializer

import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.TreeNode
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonNode
import com.gin.pixiv.response.base.WorkBody
import com.gin.pixiv.response.illustration.SimpleIllustration
import com.gin.pixiv.response.novel.SimpleNovel

/**
 * @author BX-Gin
 * @since 2024/3/2 10:08
 */
class PickupDeserializer : JsonDeserializer<List<WorkBody>>() {
    override fun deserialize(jsonParser: JsonParser?, context: DeserializationContext?): List<WorkBody>? {
        val rootNode = jsonParser?.readValueAsTree<TreeNode>()

        if (rootNode?.isArray != true) {
            return null
        }

        val list = ArrayList<WorkBody>()
        for (i in 0 until rootNode.size()) {
            val elementNode = rootNode.get(i)

            val typeNode = elementNode.get("type")
            if (typeNode is JsonNode && typeNode.isTextual) {
                when (val type = typeNode.asText()) {
                    "illust" -> list.add(
                        elementNode.traverse(jsonParser.codec).readValueAs(SimpleIllustration::class.java)
                    )

                    "novel" -> list.add(
                        elementNode.traverse(jsonParser.codec).readValueAs(SimpleNovel::class.java)
                    )

                    else -> {
                        System.err.println("unknown type $type")
                    }
                }
            }
        }

        return list
    }
}